// 基础请求配置
const BASE_URL = 'https://m1.apifoxmock.com/m1/6360638-6056593-default'; // 请替换为您的实际API地址
const TIMEOUT = 10000; // 请求超时时间

// 请求状态码
const STATUS_CODE = {
  SUCCESS: 200,
  UNAUTHORIZED: 401,
  FORBIDDEN: 403,
  NOT_FOUND: 404,
  SERVER_ERROR: 500
};

class Request {
  constructor() {
    this.baseUrl = BASE_URL;
    this.timeout = TIMEOUT;
  }

  // 请求拦截器
  requestInterceptor(config) {
    // 可以在这里添加token等认证信息
    const token = wx.getStorageSync('token');
    if (token) {
      config.header = {
        ...config.header,
        'Authorization': `Bearer ${token}`
      };
    }
    return config;
  }

  // 响应拦截器
  responseInterceptor(response) {
    const { statusCode, data } = response;
    
    if (statusCode === STATUS_CODE.SUCCESS) {
      return data;
    }
    
    // 处理错误状态码
    switch (statusCode) {
      case STATUS_CODE.UNAUTHORIZED:
        wx.showToast({
          title: '登录已过期，请重新登录',
          icon: 'none'
        });
        // 可以在这里处理登录过期逻辑
        break;
      case STATUS_CODE.FORBIDDEN:
        wx.showToast({
          title: '没有权限访问',
          icon: 'none'
        });
        break;
      case STATUS_CODE.NOT_FOUND:
        wx.showToast({
          title: '请求的资源不存在',
          icon: 'none'
        });
        break;
      case STATUS_CODE.SERVER_ERROR:
        wx.showToast({
          title: '服务器错误',
          icon: 'none'
        });
        break;
      default:
        wx.showToast({
          title: '请求失败',
          icon: 'none'
        });
    }
    
    return Promise.reject(response);
  }

  // 通用请求方法
  request(options) {
    const config = this.requestInterceptor({
      url: `${this.baseUrl}${options.url}`,
      method: options.method || 'GET',
      data: options.data,
      header: options.header || {},
      timeout: this.timeout
    });

    return new Promise((resolve, reject) => {
      wx.request({
        ...config,
        success: (res) => {
          try {
            const data = this.responseInterceptor(res);
            resolve(data);
          } catch (error) {
            reject(error);
          }
        },
        fail: (error) => {
          wx.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
          reject(error);
        }
      });
    });
  }

  // GET请求
  get(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'GET',
      data,
      ...options
    });
  }

  // POST请求
  post(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'POST',
      data,
      ...options
    });
  }

  // PUT请求
  put(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'PUT',
      data,
      ...options
    });
  }

  // DELETE请求
  delete(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'DELETE',
      data,
      ...options
    });
  }
}

// 创建单例
const request = new Request();

export default request; 